package com.example.libpicblur.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.libpicblur.R;

/**
 * FileName: LibPicColorView
 * Author: lzt
 * Date: 2022/10/29 11:15
 */
public class LibPicColorView extends View {
    private Paint mPaint;
    private boolean isDrawing = false;
    private int mPaintColor = R.color.Lib_pic_blur_bg;
    private int mRadiusTopStart, mRadiusTopEnd, mRadiusBottomStart, mRadiusBottomEnd;

    public LibPicColorView(Context context) {
        super(context);
        init();
    }

    public LibPicColorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LibPicColorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(1);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isDrawing) {
            canvas.save();
            Path mShadowPath = new Path();
            //剪裁区域
            RectF rect = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());
            mShadowPath.addRoundRect(rect, new float[]{
                    mRadiusTopStart, mRadiusTopStart,
                    mRadiusTopEnd, mRadiusTopEnd,
                    mRadiusBottomEnd, mRadiusBottomEnd,
                    mRadiusBottomStart, mRadiusBottomStart
            }, Path.Direction.CW);
            canvas.clipPath(mShadowPath);
            //绘制颜色
            canvas.drawColor(getResources().getColor(mPaintColor));
            canvas.restore();
        }
    }

    public void setColor(int color, int radiusTopStart, int radiusTopEnd, int radiusBottomStart, int radiusBottomEnd) {
        post(new Runnable() {
            @Override
            public void run() {
                isDrawing = true;
                mPaintColor = color;
                mRadiusTopStart = radiusTopStart;
                mRadiusTopEnd = radiusTopEnd;
                mRadiusBottomStart = radiusBottomStart;
                mRadiusBottomEnd = radiusBottomEnd;
                postInvalidate();
            }
        });
    }
}
